import {
  addSelfCard,
  editSelfCard,
  addOtherCard,
  editOtherCard,
  getCardDetails,
  distinguishCard,
  removeCard,
  getOSSAutograph
} from '../../apis/card';
import {
  checkUpload,
  uploadOSS,
  globalData
} from '../../utils/request'
const app = getApp();

Page({
  data: {
    isRequest: false,
    type: 'create',
    address: '请选择地区',
    region: '',
    avatar: '',
    sex: null,
    label: [],
    trade: {},
    form: {
      userName: '',
      phone: '',
      mail: '',
      company: '',
      dept: '',
      post: '',
      fax: '',
      telephone: '',
      wechat: '',
      qq: '',
      webUrl: ''
    },
    OSSAutograph: {}
  },

  onLoad(options) {
    this.setData({
      ...options
    });
    this.getOSSAutograph();
    if (options.type === 'edit' || options.type === 'otherEdit') {
      wx.setNavigationBarTitle({
        title: '编辑名片'
      });
      this.getCardInfo(options.cardId);
    } else if (options.type === 'distinguish') {
      this.distinguish(options.src);
    };
  },

  getCardInfo(id) {
    getCardDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;

        if (data.imageList) data.imageList = data.imageList.map(v => {
          if (!new RegExp('^https://').test(v) && !new RegExp('^http://').test(v)) v = app.globalData.url + v;
          return v
        });

        for (let key in this.data.options) {
          if (data[key]) {
            this.data.options[key] = true;
            this.data.optionsSelect[key] = true;
          };
        };
        this.setData({
          form: data,
          avatar: !new RegExp('^https://').test(data.avatar) && !new RegExp('^http://').test(data.avatar) ? app.globalData.url + data.avatar : data.avatar,
          avatarUrl: data.avatar,
          region: data.address ? data.address : '北京市北京市东城区',
          sex: data.gender,
          label: data.label,
          trade: {
            name: data.industry,
            industryId: data.industryId
          },
          options: this.data.options,
          optionsSelect: this.data.optionsSelect
        });
      };
    });
  },
  // 识别名片信息
  distinguish(path) {
    distinguishCard(path).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        this.setData({
          form: data,
          region: data.address ? data.address : '北京市北京市东城区'
        });
      };
    });
  },
  // 选择头像
  selectAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let {
          tempFilePaths
        } = res;
        this.setData({
          avatar: tempFilePaths[0]
        });
        // wx.navigateTo({
        //   url: `/pages/tailoring/index?src=${tempFilePaths[0]}`
        // });
      }
    });
  },
  // 选择性别
  changeSex(e) {
    let {
      sex
    } = e.currentTarget.dataset;
    this.setData({
      sex: sex
    });
  },
  // 添加标签
  changeLabel() {
    if (this.data.label.length === 0) {
      wx.navigateTo({
        url: '/pages/addLabel/index'
      });
    } else {
      wx.navigateTo({
        url: `/pages/addLabel/index?list=${JSON.stringify(this.data.label)}`
      });
    };
  },
  // 选择地址
  changeAddress(e) {
    this.setData({
      region: e.detail.value.join('')
    });
  },
  // 选择行业
  changeTrade() {
    wx.navigateTo({
      url: '/pages/selectTrade/index'
    });
  },
  // 修改图片
  changeImages() {
    wx.navigateTo({
      url: `/pages/uploadImages/index?type=edit&cardId=${this.data.cardId}`
    });
  },

  // OSS签名
  getOSSAutograph() {
    getOSSAutograph().then(res => {
      if (res.data.code === 200) {
        this.setData({
          OSSAutograph: res.data.data
        });
      };
    });
  },

  // 上传
  upload(form) {
    wx.showToast({
      title: '请稍等...',
      icon: 'loading',
      duration: 99999,
      mask: true
    });
    checkUpload(this.data.avatar).then(res => {
      let {
        code
      } = JSON.parse(res.data);
      if (code === 200) {
        let fileName = globalData.userId + '-' + new Date().getTime() + '.png';
        uploadOSS(this.data.avatar, this.data.OSSAutograph.host, {
          key: `${this.data.OSSAutograph.dir}/${fileName}`,
          policy: this.data.OSSAutograph.policy,
          OSSAccessKeyId: this.data.OSSAutograph.accessid,
          signature: this.data.OSSAutograph.signature,
          success_action_status: '200'
        }).then(res => {
          if (res.statusCode === 200) {
            form.avatar = `${this.data.OSSAutograph.host}/${this.data.OSSAutograph.dir}/${fileName}`;
            if (this.data.type === 'addOther' || this.data.type === 'distinguish') {
              this.createOtherCard(form);
            } else if (this.data.type === 'edit') {
              this.editMycard(form);
            } else if (this.data.type === 'otherEdit') {
              this.editOtherCard(form);
            } else {
              this.createMyCard(form);
            };
          };
        });
      } else {
        wx.showToast({
          title: '头像违规，请重新上传',
          icon: 'none'
        });
      };
    });
  },
  // 提交
  bindsubmit(e) {
    let {
      value
    } = e.detail;

    for (let key in value) {
      if (value[key] === '') {
        delete value[key]
      };
    };

    // 头像
    if (this.data.avatar === '') {
      wx.showToast({
        title: '请选择头像',
        icon: 'none'
      });
      return
    } else {
      value.avatar = this.data.avatarUrl;
    };

    // 标签
    if (this.data.label.length !== 0) {
      value.label = this.data.label;
    };

    if (this.data.trade.name) {
      value.industryId = this.data.trade.industryId;
    };

    // 名字
    if (!value.userName) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none'
      });
      return
    };

    if (!this.data.sex) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return
    } else {
      value.gender = this.data.sex;
    };

    // 电话
    if (!value.phone) {
      wx.showToast({
        title: '请填写电话号码',
        icon: 'none'
      });
      return
    } else if (value.phone && value.phone.length !== 11) {
      wx.showToast({
        title: '请正确填写电话号码',
        icon: 'none'
      });
      return
    };

    // 公司
    if (!value.company) {
      wx.showToast({
        title: '请填写公司',
        icon: 'none'
      });
      return
    };

    if (value.mail && !new RegExp('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$').test(value.mail)) {
      wx.showToast({
        title: '请正确填写邮箱地址',
        icon: 'none'
      });
      return
    };

    if (this.data.region) value.address = this.data.region;

    if (this.data.type === 'edit') {
      value.images = this.data.form.images
    } else {
      value.images = this.data.images;
    };

    if (this.data.type === 'addOther' || this.data.type === 'distinguish') {
      this.upload(value);
      // this.createOtherCard(value);
    } else if (this.data.type === 'edit') {
      if (new RegExp('^wxfile://').test(this.data.avatar) || new RegExp('^http://tmp').test(this.data.avatar)) this.upload(value);
      else this.editMycard(value);
      // this.editMycard(value);
    } else if (this.data.type === 'otherEdit') {
      if (new RegExp('^wxfile://').test(this.data.avatar) || new RegExp('^http://tmp').test(this.data.avatar)) this.upload(value);
      else this.editOtherCard(value);
      // this.editOtherCard(value);
    } else {
      this.upload(value);
      // this.createMyCard(value);
    };
  },
  // 创建自己的名片
  createMyCard(form) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    addSelfCard({
      ...form
    }).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        wx.showToast({
          title: '制作成功',
          icon: 'success',
          duration: 1000,
          mask: true,
          success: res => {
            let timer = setTimeout(() => {
              wx.navigateBack({
                delta: 2
              });
              clearTimeout(timer);
            }, 1000);
          }
        });
      };
    });
  },
  // 创建他人名片
  createOtherCard(form) {
    delete form.images;
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    addOtherCard({
      ...form
    }).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        wx.showToast({
          title: '制作成功',
          icon: 'success',
          duration: 1000,
          mask: true,
          success: res => {
            let timer = setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
              clearTimeout(timer);
            }, 1000);
          }
        });
      };
    });
  },
  // 修改自己的名片
  editMycard(form) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    editSelfCard({
      ...form,
      cardId: this.data.cardId
    }).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          mask: true,
          duration: 1000,
          success: res => {
            let timer = setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
              clearTimeout(timer);
            }, 1000);
          }
        });
      };
    });
  },
  // 修改通讯录名片
  editOtherCard(form) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    delete form.images;
    editOtherCard({
      ...form,
      cardId: this.data.cardId
    }).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          mask: true,
          duration: 1000,
          success: res => {
            let timer = setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
              clearTimeout(timer);
            }, 1000);
          }
        })
      };
    });
  },
  // 删除卡片
  deleteCard() {
    wx.showModal({
      title: '删除',
      content: '确定删除此名片吗',
      success: res => {
        if (res.confirm) {
          removeCard(this.data.cardId).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1000,
                success: () => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1,
                    });
                    clearTimeout(timer);
                  }, 1000);
                }
              });
            };
          });
        };
      }
    });
  }
})